#lang web-server/insta

(struct post(title body))

(define BLOG
  (list (post "first post" "this is my first post")
        (post "second post" "this is my another post")))
(define (start request)
  (render-blog-page BLOG request))

(define (parse-post bindings)
  (post (extract-binding/single 'title bindings)
        (extract-binding/single 'body bindings)))

(define (render-blog-page a-blog request)
  (local [(define (response-generator make-url)
            (response/xexpr
             `(html (head (title "My Blog"))
                    (body
                     (h1 "My Blog")
                     ,(render-posts a-blog)
                     (form ((method "post")(action, (make-url insert-post-handler)))
                           (input ((name "title")))
                           (input ((name "body")))
                           (input ((type "submit"))))))))
          (define (insert-post-handler request)
            (render-blog-page
             (cons (parse-post (request-bindings request))
                   a-blog)
             request))]
    (send/suspend/dispatch response-generator)))

(define (render-post a-post)
  `(div ((class "post"))
        ,(post-title a-post)
        (p,(post-body a-post))))

(define (render-posts a-blog)
  `(div ((class "posts"))
        ,@(map render-post a-blog)))